package com.clayecloud.lib_common.utils;

import com.clayecloud.lib_base.config.BaseConfig;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpUtil {
    private static OkHttpClient httpClient = new OkHttpClient.Builder()
            // 设置拦截器，添加统一的请求头
            .addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    // 以拦截到的请求为基础建立一个新的请求对象，而后插入Header
                    Request request = chain.request().newBuilder()
                            .addHeader("Authorization",getToken() )
                            .build();
                    // 开始请求
                    return chain.proceed(request);
                }
            })
            .build();

    private  static Retrofit retrofit =new Retrofit.Builder()
            .client(httpClient)
            .baseUrl(BaseConfig.HOST_URL) //设置网络请求的Url地址
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();

    //提供一个公有的静态方法，返回实例对象
    public static Retrofit getInstance() {
        return retrofit;
    }

    //获取token
    private static String getToken(){
        return LoginUtil.getUserID()==0?TempData.getTempToken():LoginUtil.getUserToken(LoginUtil.getUserID());
    }


}
